/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/
import React, { Component } from 'react';
import {high,base,ajax,getMultiLang} from 'nc-lightapp-front';
const { Refer} = high;
const { NCButton: Button, NCTable: Table, NCCheckbox: Checkbox, NCModal:Modal, NCDiv, NCHotKeys:HotKeys, NCTooltip } = base;
import drawinAssidData from '../drawingAssidData/index.js';
import './index.less';
import {constClassId} from "../assidDbModalVersion/const.js";
const modalStyle = { minHeight: '268px', maxHeight: '470px' }
  const defaultProps12 = {
    prefixCls: "bee-table",
    multiSelect: {
      type: "checkbox",
      param: "key"
    }
  };
  const format = 'YYYY-MM-DD';
  const timeFormat = 'YYYY-MM-DD HH:mm:ss';
export default class AssidModal extends Component {
    constructor(props) {
        super(props);

        let showDisableData = true;
        if(props.hasOwnProperty('showDisableData') ){
            if(props.showDisableData != 'show'){
                showDisableData = false;
            }
        }
        this.state = {
            json:{},
            showModal:false,
            isShowUnit:false,//是否显示业务单元
            assData: [//辅助核算信息
            ],
            childAssData:[],//接受父组件传过来的参数
            loadData:[],//查询模板加载数据
            listItem:{},//模板数据对应值
            checkedAll:true,//默认全选中
            SelectedAssData:[],//选中的数据
            checkedArray: [],
            assidData: {}, //key=assid,value=assData
			assitemData: {} //key=pk_accasoa+prepareddate,value=assitems
        };
        this.close = this.close.bind(this);
        this.moduleId = "assid";
		this.ViewModel = this.props.ViewModel;
    }
    componentWillMount(){
		let callback= (json) =>{
            this.setState({
              json:json
				},()=>{
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    componentWillReceiveProps (nextProp) {
        /** 
            *父组件传递过来的pretentAssData里包含 
            *   pk_accountingbook,
            *   pk_accasoa,
            *   prepareddate,
            *   pk_org,
            *   assData,
            *   assid,
            *   checkboxShow,是否显示复选框 true、false
            *   checkedAll 是否全选中 true， false
            *   pk_defdoclist,
            */ 
            let self=this;
            let {checkedAll,assData,checkedArray,childAssData}=self.state;
            let {pretentAssData}=nextProp;
        if(nextProp.showOrHide&&childAssData!=pretentAssData){              
            childAssData=pretentAssData;
            if(typeof pretentAssData.checkedAll==='boolean'){//接收父组件传递过来的checkedAll
                checkedAll=pretentAssData.checkedAll;
            }else{
                checkedAll=true;
            }
            if(pretentAssData.assid){
                checkedArray=[];
                let assidParam={
                    pk_accasoa:pretentAssData.pk_accasoa,
                    date:pretentAssData.prepareddate,
                    assid:pretentAssData.assid,
                    isNeedVersion:self.props.isNeedVersion
                }
                ajax({
                    url:'/nccloud/gl/voucher/queryAssTypeAndValue.do',
                    data:assidParam,
                    success: function(response){
                        const { data,success } = response;
                        if(data){
                            if(data.length>0){
                                data.map((item,index)=>{
                                    if(item.pk_Checkvalue && item.pk_Checkvalue=="~"){
                                        item.pk_Checkvalue=null;
                                    }
                                    item.key=index;
                                    checkedArray.push(checkedAll);
                                    item.m_classid=item.classid;
                                    item.pk_Checktype=item.pk_accassitem;
                                })
                            }
                        }
                        childAssData.assData=data;
                        self.setState({
                            assData:data,
                            childAssData,checkedAll,checkedArray
                        }, ()=>{
                            // self.autoFocus()
                        })
                    }
                })
            }else if(pretentAssData.assData.length>0){
                checkedArray=[];
                pretentAssData.assData.map((item,index)=>{
                    if(!pretentAssData.checkboxShow){
                        checkedArray.push(true);
                    } else {
                        checkedArray.push(checkedAll);
                    }             
                })
                self.setState({
                    assData:pretentAssData.assData,
                    childAssData,checkedArray,checkedAll
                },()=>{
                    // self.autoFocus()
                })
            }else{
                assData=[];
                checkedArray=[];
                //请求辅助核算数据
                let url = '/nccloud/gl/voucher/queryAssItem.do';
                let queryData = {
                    pk_accasoa:pretentAssData.pk_accasoa,
                    prepareddate: pretentAssData.prepareddate,
                };

                /* 是否包含下级科目辅助核算，默认不包含 */
                if(nextProp.hasOwnProperty('includeSubAss') && nextProp.includeSubAss){
                    queryData.includeSub = nextProp.includeSubAss;
                }
                ajax({
                    url:url,
                    data:queryData,
                    success: function(response){
                        const { success } = response;
                        //渲染已有账表数据遮罩
                        if (success) {
                            if(response.data){
                                if(response.data.length>0){
                                    response.data.map((item,index)=>{
                                        item.key=index;
                                        checkedArray.push(checkedAll);
                                        let obj={
                                            key:index,
                                            "checktypecode":item.code,
                                            "checktypename" :item.name,
                                            "pk_Checktype": item.pk_accassitem,
                                            "refCode":item.refCode?item.refCode:item.code,
                                            "refnodename":item.refnodename,
                                            "pk_accassitem":item.pk_accassitem,
                                            "m_classid":item.classid,
                                            "classid":item.classid,
                                            "pk_defdoclist":item.classid,
                                            "pk_accountingbook":childAssData.pk_accountingbook,
                                            "inputlength":item.inputlength?item.inputlength:'', 
                                            "digits":item.digits?item.digits:'0'

                                        }
                                        assData.push(obj);
                                    })
                                    
                                }
                            }
                            childAssData.assData=assData;
                            self.setState({
                                assData,childAssData,checkedAll,checkedArray
                            }, ()=>{
                                // self.autoFocus()
                            })
                        }   
                    }
                });
            }
        }
    }
    

    //表格操作根据key寻找所对应行
	findByKey(key, rows) {
		let rt = null;
		let self = this;
		rows.forEach(function(v, i, a) {
			if (v.key == key) {
				rt = v;
			}
		});
		return rt;
    }
    //自动获取焦点 单选时,自动获取焦点后全文检索有问题，先去掉
    // autoFocus=()=>{
	// 	let self=this;
	// 	if(self.props.hotKeyboard){
	// 		setTimeout(() => {
	// 			let modelNode= ReactDOM.findDOMNode(self.Modal);
	// 			let inputNode=modelNode&&modelNode.querySelector('#assDataModal input:not([tabindex="-1"])');
	// 			if(this.props.ViewModel){
	// 				this.props.ViewModel.shouldAutoFocus = true;//bbqin让加的
	// 			}
	// 			if(inputNode){
	// 				inputNode&&inputNode.focus()
	// 			}
	// 			if(this.props.ViewModel){
	// 				this.props.ViewModel.shouldAutoFocus = false;
	// 			}
	// 		}, 500);
	// 	}
    // }
    
    close() {
        this.props.handleClose();
    }
    //确定 过滤勾选的数据
    confirm=()=>{
        let self=this;
        let { SelectedAssData,checkedArray,listItem,assData,childAssData } =self.state;
        SelectedAssData=[];//清空
        let url = '/nccloud/gl/voucher/queryAssId.do';
        for(var i = 0; i < checkedArray.length; i++){
            if(checkedArray[i]==true){
                SelectedAssData.push(assData[i]);
            }
        }
        let sendData={};
        let assid='',assname='';
        if(self.props.pretentAssData.type&&self.props.pretentAssData.type=='contrast'){//内部交易明细对账，汇总对账
            sendData={
                data:SelectedAssData,
                assid:assid,
                assname:assname
            }
            self.props.onConfirm(sendData);
            return;
        }
        if(SelectedAssData.length>0){
            let parm={"ass":SelectedAssData,"pk_accountingbook":childAssData.pk_accountingbook};            
            ajax({
                url:url,
                data:parm,
                async:false,
                success:function(response){
                    
                    let { data }=response;
                    if(data){
                        assid = data.assid;
                        assname=data.assname?data.assname:'';
                        sendData={
                            data:SelectedAssData,
                            assid:assid,
                            assname:assname
                        }            
                        self.props.onConfirm(sendData);
                    }
                }
            })
        } else{
            sendData={
                data:SelectedAssData,
                assid:assid,
                assname:assname
            }            
            self.props.onConfirm(sendData);
        }    
    }
    //返回多版本refurl
    changeRefUrl=(record)=>{
		//let referUrl = record.refnodename + '.js';
		let referUrl=record.refnodename;
		if(constClassId[record.classid]){
			referUrl=constClassId[record.classid];
		}
        //内部客商
		if(record.refnodename=="uapbd/refer/supplier/InnerCustSupplierGridTreeRef/index"){
			referUrl='uapbd/refer/supplier/InnerCustSupplierVersionGridTreeRef/index';
		}
		return referUrl+'.js';
	}
    //版本参照取值
	getReferValOfVersion=(record,val)=>{
		let refVal=val.refpk;
		if(constClassId[record.classid]){
			refVal=(val.values&&val.values.pk_dept&&val.values.pk_dept.value)||
			(val.values&&val.values.pk_profitcenter&&val.values.pk_profitcenter.value)||
			(val.values&&val.values.pk_customer&&val.values.pk_customer.value)||
			(val.values&&val.values.pk_supplier&&val.values.pk_supplier.value)||
			(val.values&&val.values.pk_cust_sup&&val.values.pk_cust_sup.value)||
			(val.values&&val.values.oid&&val.values.oid.value)||val.refpk;
		}
		return refVal;
	}
    //全选
    onAllCheckChange = () => {
        let self = this;
        let checkedArray = [];
        let selIds = [];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
          checkedArray[i] = !self.state.checkedAll;
        }
        self.setState({
          checkedAll: !self.state.checkedAll,
          checkedArray: checkedArray,
        });
      };
      //单选
      onCheckboxChange = (text, record, index) => {
        let self = this;
        let allFlag = false;
        let checkedArray = self.state.checkedArray.concat();
        checkedArray[index] = !self.state.checkedArray[index];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
          if (!checkedArray[i]) {
            allFlag = false;
            break;
          } else {
            allFlag = true;
          }
        }
        self.setState({
          checkedAll: allFlag,
          checkedArray: checkedArray,
        });
      };
      
      renderColumnsMultiSelect(columns) {
        const {checkedArray } = this.state;
        const { multiSelect } = this.props;
        let select_column = {};
        let indeterminate_bool = false;
        if (multiSelect && multiSelect.type === "checkbox") {
          let i = checkedArray.length;
          while(i--){
              if(checkedArray[i]){
                indeterminate_bool = true;
                break;
              }
          }
          let defaultColumns = [
            {
              title: (
                <span fieldid="firstcol">
                    <Checkbox
                    className="table-checkbox"
                    checked={this.state.checkedAll}
                    indeterminate={indeterminate_bool&&!this.state.checkedAll}
                    onChange={this.onAllCheckChange}
                    />
                </span>
              ),
              key: "checkbox",
              attrcode: 'checkbox',
              dataIndex: "checkbox",
              width: "60px",
              render: (text, record, index) => {
                return (
                    <span fieldid='firstcol'>
                        <Checkbox
                            className="table-checkbox"
                            checked={this.state.checkedArray[index]}
                            onChange={this.onCheckboxChange.bind(this, text, record, index)}
                        />
                  </span>
                );
              }
            }
          ];
          columns = defaultColumns.concat(columns);
        }
        return columns;
      }

    render() {
        let{showOrHide,pretentAssData, hotKeyboard}=this.props;
        let { loadData,assData} =this.state;
        let columnsldad;
        let {json}=this.state
        let showDisableData = true;
        if(this.props.hasOwnProperty('showDisableData') ){
            if(this.props.showDisableData != 'show'){
                showDisableData = false;
            }
        }
        let defWidth = pretentAssData.checkboxShow ? 196 : 226
        let columns10=[
            {
              title: (<div fieldid='checktypecode'>{this.state.json['publiccomponents-000001']}</div>),/* 国际化处理： 核算类型编码*/
              dataIndex: "checktypecode",
              key: "checktypecode",
              width: '100',
              render: (text, record, index) => {
				return <div fieldid='checktypecode'>{record.checktypecode ? <span>{record.checktypecode}</span> : <span>&nbsp;</span>}</div>;
			    }
            },
            {
                title: (<div fieldid='checktypename'>{this.state.json['publiccomponents-000002']}</div>),/* 国际化处理： 核算类型名称*/
                dataIndex: "checktypename",
                key: "checktypename",
                width: defWidth,
                render: (text, record, index) => {
                    return <div fieldid='checktypename'>{record.checktypename}</div>;
                //   return <div fieldid='checktypename'>{record.isempty==false?<span className="requireItem">*</span>:<div/>}{record.checktypename}</div>;
                  }
              },
            {
              title: (<div fieldid='checkvaluename'>{this.state.json['publiccomponents-000003']}</div>),/* 国际化处理： 核算内容*/
              dataIndex: "checkvaluename",
              key: "checkvaluename",
              width: defWidth,
                render: (text, record, index) => {
                    return (drawinAssidData(this,text, record, index,showDisableData))
                }
            }
        ];
        if(pretentAssData.checkboxShow){//复选框显示true
            columnsldad = this.renderColumnsMultiSelect(columns10);
        }else{
            columnsldad=columns10;
        }
        let tipOK = (<div>{`${this.state.json['publiccomponents-000009']}(Alt+Y)`}</div>)
        let tipCancel = (<div>{`${this.state.json['publiccomponents-000010']}(Alt+N)`}</div>)
            
        return (
            <div className="nc_group">
                <Modal
                    // className={'msg-modal'}
                    fieldid = {this.moduleId}
                    id='assDataModal'
                    show={showOrHide }
                    backdrop='static'
                    //show={true}
                    // backdrop={ this.state.modalDropup }
                    onHide={ this.close }
                    animation={true}
                    className="AssidModalaa"
                    onEntered={()=>{
                        // this.autoFocus()
                    }}
                    ref={Modal => (this.Modal = Modal)}
                    >
                    <HotKeys
                        keyMap={{
                            sureBtnHandler: ["alt+y"],
                            cancelBtnHandler: ["alt+n"]
                        }}
                        handlers={{
                            sureBtnHandler: () => {
                                // 确定按钮的事件 增加top的判断避免所有弹窗逻辑都被触发  by bbqin
                                if (this.Modal && this.Modal.isTopModal()) {
									this.confirm()
                                }
                            },
                            cancelBtnHandler: () => {
                                // 取消按钮的事件  增加top的判断避免所有弹窗逻辑都被触发  by bbqin
                                if (this.Modal && this.Modal.isTopModal()) {
									this.close();
                                }
                            }
                        }}
                        className="hotkeys-wrapper"
                        focused={true}
                        attach={document.body}
                    />
                    <Modal.Header closeButton>
                        <Modal.Title>{this.state.json['publiccomponents-000008']}</Modal.Title>{/* 国际化处理： 辅助核算*/}
                    </Modal.Header >
                    <Modal.Body>
                        <NCDiv fieldid="assid" areaCode={NCDiv.config.TableCom}>
                            <Table
                                columns={columnsldad}
                                addBlankCol={false}
                                inModal={true}
                                data={assData}
                                bodyStyle={{height: 296}}
                                scroll={{x:true, y: 296}}
                            />
                        </NCDiv>
                    </Modal.Body>
                    <Modal.Footer>
                    <NCTooltip trigger="hover" placement="top" inverse={true} className='model-helper-overlay' overlay={tipOK}>
                        <Button fieldid='confirm' colors="primary" onClick={ this.confirm } tabindex="0">
                             {this.state.json['publiccomponents-000009']} (<span class='text-decoration-underline'>Y</span>) {/* 国际化处理： 确定*/}
                        </Button>
                    </NCTooltip>
                    <NCTooltip trigger="hover" placement="top" inverse={true} className='model-helper-overlay' overlay={<div>{tipCancel}</div>}>
                        <Button fieldid='cancel' onClick={ this.close }> 
                            {this.state.json['publiccomponents-000010']}(<span class='text-decoration-underline'>N</span>) {/* 国际化处理： 取消*/}
                        </Button>
                    </NCTooltip>
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }
}
AssidModal.defaultProps = defaultProps12;
// export default function (props = {}) {
//     var conf = {
//     };

//     return <AssidModal {...Object.assign(conf, props)} />
// }

/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/